/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-01-05 14:35:32
 * @LastEditTime: 2023-09-04 10:36:44
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import {
  autoBatchEnhancer,
  combineReducers,
  configureStore,
} from '@reduxjs/toolkit';
import { api } from '@tourfly/api';

import { rememberEnhancer, rememberReducer } from 'redux-remember';

import profileReducer from './profileSlice';

import userReducer from './user';

import { LOCALSTORAGE_PREFIX } from '@/config/constants';
import changeBoardModalReducer from '@/features/ChangeBoardModal/store/slice';
import boardsReducer from '@/features/Gallery/store/boardSlice';
import galleryReducer from '@/features/Gallery/store/gallerySlice';

const allReducers = {
  user: userReducer,
  changeBoardModal: changeBoardModalReducer,
  profile: profileReducer,
  gallery: galleryReducer,
  boards: boardsReducer,
  [api.reducerPath]: api.reducer,
};
const rootReducer = combineReducers(allReducers);
const rememberedRootReducer = rememberReducer(rootReducer);

const rememberedKeys: (keyof typeof allReducers)[] = [];

export const store = configureStore({
  reducer: rememberedRootReducer,
  enhancers: (existingEnhancers) => {
    return existingEnhancers
      .concat(
        rememberEnhancer(window.localStorage, rememberedKeys, {
          persistDebounce: 300,
          prefix: LOCALSTORAGE_PREFIX,
        })
      )
      .concat(autoBatchEnhancer());
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      immutableCheck: false,
      serializableCheck: false,
    }).concat(api.middleware),
  devTools: {
    // Uncommenting these very rapidly called actions makes the redux dev tools output much more readable
    actionsDenylist: ['@@REMEMBER_PERSISTED'],
  },
});

export type AppGetState = typeof store.getState;

// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
export const stateSelector = (state: RootState) => state;
export default store;
